package com.cc.controller;

import com.cc.entity.R;
import com.cc.enums.HttpEnum;
import org.apache.log4j.Logger;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


@RestControllerAdvice
public class GlobalException {

    private static final Logger logger = Logger.getLogger(GlobalException.class);
    //校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpServletRequest request){

        logger.error("请求地址{" + request.getRequestURI() + "}," +
            "{" + request.getMethod() + "}请求参数校验失败," +
                e.getBindingResult().getFieldError().getDefaultMessage());
        return R.fail(HttpEnum.VALIDATE_ERROR.getCode(),
                e.getBindingResult().getFieldError().getDefaultMessage());
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request){

        logger.error("请求地址{" + request.getRequestURI() + "}," + "不支持{" + request.getMethod() + "}请求");
        return R.fail(HttpEnum.BAD_METHOD.getCode(), HttpEnum.BAD_METHOD.getMessage());
    }
}
